/*
 * Copyright 2009 Michal Trzcinka
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed
 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 * 
 */

YAHOO.namespace('TRZCINKA.VCARD');

(function() {

  var Dom = YAHOO.util.Dom,
  DDTarget = YAHOO.util.DDTarget,
  Constants = YAHOO.TRZCINKA.VCARD.Constants,
  Config = YAHOO.TRZCINKA.VCARD.Config,
  JSON = YAHOO.lang.JSON,
  Event = YAHOO.util.Event,
  LOGGER = new YAHOO.widget.LogWriter('view.js'),
  Map = YAHOO.TRZCINKA.VCARD.Map,
  Link = YAHOO.TRZCINKA.VCARD.Link;

  LOGGER.log('Initializing TRZCINKA.VCARD.GridView module...', 'info');

  /**
   * GridView
   */

  YAHOO.TRZCINKA.VCARD.GridView = function(parent, gridModel) {
    LOGGER.log('instantiating GridView', 'debug');

    var cells;
    var links = [];
    var wrapper;

    var eventHandler = function(type, args) {
      var data = args[0][1];
      type = args[0][0];

      LOGGER.log('View received event on model change: type ' + type + ', eventData: ' + JSON.stringify(data), 'debug');

      switch (type) {
        case Constants.MODEL_LOADED_EVENT:

          LOGGER.log('View building grid view because of gridLoaded event received', 'debug');

          wrapper = document.createElement('div');
          wrapper.id = Constants.PAINT_WRAPPER_ID;
          Dom.setStyle(wrapper, 'position', 'relative');
          parent.appendChild(wrapper);

          cells = new YAHOO.TRZCINKA.VCARD.Cells(gridModel, wrapper, data.rows, data.columns);

          if (data.items) {

            var locationsItems = new Map();
            data.items.each(function(item) {
              var location = item.location.gridLocationToString();
              if (locationsItems.containsKey(location)) {
                locationsItems.get(location).push(item);
              } else {
                locationsItems.add(location, [item]);
              }
            });

            locationsItems.each(function(pair) {
              var items = pair.value;
              items.sort(YAHOO.TRZCINKA.VCARD.MODEL.byOrder);
              items.each(function(item) {
                cell = cells.getCell(pair.key.fromGridLocation());
                cell.itemSaved(item);
              });

            });
          }

          if (data.links) {
            data.links.each(function(linkModel) {
              links.push(new Link(linkModel.from, linkModel.to, wrapper));
            })

          }

          if (gridModel.accountType == Constants.ACCOUNT_TYPE_OPERATOR) {
            YAHOO.TRZCINKA.VCARD.Item._editor = new YAHOO.TRZCINKA.VCARD.ItemEditor(gridModel);
            YAHOO.TRZCINKA.VCARD.DimensionsEditor._editor = new YAHOO.TRZCINKA.VCARD.DimensionsEditor(gridModel);
          }
          break;

        case Constants.ITEM_SAVED_EVENT:

          LOGGER.log('View saving item because of itemSavedEvent event received', 'debug');

          cell = cells.getCell(data.location);
          cell.itemSaved(data);

          break;

        case Constants.ITEM_REMOVED_EVENT:

          LOGGER.log('View removing  item because of itemRemovedEvent event received', 'debug');
          cell = cells.getCell(data.location);
          cell.itemRemoved();

          break;

        case Constants.ITEM_MOVED_EVENT:

          LOGGER.log('View moving item because of itemMovedEvent event received', 'debug');
          cells.getCell(data.oldLocation).itemMoved(cells.getCell(data.newLocation), data.order);
          break;

        case Constants.STACK_MOVED_EVENT:
          LOGGER.log('View moving stack because of stackMovedEvent event received', 'debug');
          cells.getCell(data.oldLocation).stackMoved(cells.getCell(data.newLocation));
          break;

        case Constants.ITEM_UPDATED_EVENT:
          LOGGER.log('Updating because of itemUpdatedEvent event received', 'debug');
          cells.getCell(data.location).updated(data);
          break;

        case Constants.TOP_ITEM_SET_EVENT:
          LOGGER.log('Setting top item because of topItemSetEvent event received', 'debug');
          cells.getCell(data.location).topItemSet(data);
          break;

        case Constants.ITEMS_LINKED_EVENT:
          LOGGER.log('Linking items because of itemsLinkedEvent event received', 'debug');
          links.push(new Link(data.from, data.to, wrapper));
          break;

        case Constants.ITEMS_UNLINKED_EVENT:
          LOGGER.log('unlinking items because of itemsLinkedEvent event received', 'debug');
          var removed = links.remove(function(link) {
            return link.from.equals(data.location1) && link.to.equals(data.location2) ||
            link.from.equals(data.location2) && link.to.equals(data.location1);
          });
          removed.destroy();
          break;

        case Constants.DIMENSIONS_CHANGED_EVENT:
          LOGGER.log('changing dimensions because of dimensionsChangedEvent event received', 'debug');
          YAHOO.lang.later(1000, location, function() {
            this.reload(true);
          });
          break;

        default:
          LOGGER.log('Unknown event: ' + type, 'error');
      }

    };

    gridModel.gridModelEvent.subscribe(eventHandler);

    var msgsDiv = Dom.get(Constants.MESSAGES_DIV_ID);
    var messageEventHandler = function(type, args) {
      msgsDiv.innerHTML = args[0];
    };

    Event.onContentReady(Constants.MESSAGES_DIV_ID, function () {
      gridModel.messageEvent.subscribe(messageEventHandler);  
    });
  };


})();
